package com.example.smartcity_poverty.ui.PersonalCenter.activity

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import com.example.smartcity_poverty.R
import com.example.smartcity_poverty.logic.network.AppApi
import com.example.smartcity_poverty.logic.network.ServiceNET.Companion.create
import com.example.smartcity_poverty.logic.util.Util.show
import kotlinx.android.synthetic.main.activity_new_pass_word.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

class NewPassWordActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        setContentView(R.layout.activity_new_pass_word)
        title = "修改密码"


        // 修改密码
        newPassOk.setOnClickListener {
            getSharedPreferences("token", Context.MODE_PRIVATE).apply {
                val token = getString("token", "").toString()
                GlobalScope.launch(Dispatchers.Main){
                    create<AppApi>().newPwd(token, JSONObject().apply {
                        put("oldPassword", newPass1.text.toString())
                        put("newPassword", newPass2.text.toString())
                    }.toString().toRequestBody("application/json".toMediaTypeOrNull())).apply {
                        if (this.code == "200"){
                            runOnUiThread {
                                this.msg.show()
                            }
                        }else runOnUiThread { this.msg.show() }
                    }
                }
            }

        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }
}
